#include "net.h"

int main(int argc, const char *argv[])
{
	int fd;
	struct sockaddr_in sin;
	char buf[32];
	int real_read;
	//填充结构体sin信息
	bzero(&sin,sizeof(sin));
	sin.sin_family = AF_INET;
	inet_pton(AF_INET,SERV_IP_ADDR,&sin.sin_addr);
	sin.sin_port = htons(SERV_PORT);

	if( -1 == (fd = socket(AF_INET,SOCK_STREAM,0)) )
	{//1.创建套接字
		perror("socket failed");
		return -1;
	}

	if( -1 == connect(fd,(struct sockaddr*)&sin,sizeof(sin)) )
	{//2.请求连接目标服务器端口
		perror("connect failed");
		return -1;
	}
	while(1)
	{//3.进行通信
		bzero(buf,sizeof(buf));

		printf(">");

		fgets(buf,32,stdin);

		write(fd,buf,strlen(buf)-1);

		if( 0 == (strncasecmp(buf,QUIT_STR,strlen(QUIT_STR))) )
		{
			printf("client quit\n");
			break;
		}

		bzero(buf,sizeof(buf));
		if( 0 == (strncasecmp(buf,QUIT_STR,strlen(QUIT_STR))) )
		{
			printf("client quit\n");
			break;
		}

		if( (real_read = read(fd,buf,sizeof(buf))) < 0 )
		{
			perror("read");
			return -1;
		}

		if(0 == real_read)
		{
			break;
		}

		printf("Received: %s\n",buf);

		if( 0 == (strncasecmp(buf,QUIT_STR,strlen(QUIT_STR))) )
		{
			printf("client quit\n");
			break;
		}
	}


	//关闭套接字
	close(fd);
	return 0;
}
